package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.MyResult;
import com.api.shopapi.entity.PreCheck;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.*;

import com.api.shopapi.service.*;
import com.api.shopapi.util.DoubleUtil;
import com.api.shopapi.util.Util;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 入住
 */
@RestController
@RequestMapping("Checkin")
public class CheckinController extends BaseController {

    @Autowired
    @Qualifier("CheckinServiceImplOne")
    private CheckinService checkinService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;

    @Autowired
    @Qualifier("CheckinSetmealServiceImplOne")
    private CheckinSetmealService checkinSetmealService;

    @Autowired
    @Qualifier("BerthServiceImplOne")
    private BerthService berthService;

    @Autowired
    @Qualifier("RoomServiceImplOne")
    private RoomService roomService;

    @Autowired
    @Qualifier("BuildingServiceImplOne")
    private BuildingService buildingService;


    @Autowired
    @Qualifier("RetreatSettleServiceImplOne")
    private RetreatSettleService retreatSettleService;

    @Autowired
    @Qualifier("NursingLevelServiceImplOne")
    private NursingLevelService nursingLevelService;

    @Autowired
    @Qualifier("NursingLevelItemRelServiceImplOne")
    private NursingLevelItemRelService nursingLevelItemRelService;

    @Autowired
    @Qualifier("NursingItemServiceImplOne")
    private NursingItemService nursingItemService;

    @Autowired
    @Qualifier("RoomTypeServiceImplOne")
    private RoomTypeService roomTypeService;


    @Autowired
    @Qualifier("InstitutionStaffRelServiceImplOne")
    private InstitutionStaffRelService institutionStaffRelService;


    @Autowired
    @Qualifier("ElderlyCheckinAssessWaitServiceImplOne")
    private ElderlyCheckinAssessWaitService elderlyCheckinAssessWaitService;



    /**
     * 签约入住
     */
    @RequestMapping(value = "Add", method = RequestMethod.POST)
    public MyResult Add(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String elderlyCode = jsonObject.getString("elderlyCode");

            //收费类型：1：套餐类型入住收费，2：自选配收费
            int chargeType = jsonObject.getInteger("chargeType");

            String checkinSetmealCode = jsonObject.getString("checkinSetmealCode");
            String berthCode = jsonObject.getString("berthCode");

            //入住单价元/月
            double price = 0;

            int type = jsonObject.getInteger("type");
            //自选入住是传选中的收费参数
            JSONArray feeArr = jsonObject.getJSONArray("feeArr");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            Checkin checkin = checkinService.getByElderlyCodeAndInstitutionCode(elderlyCode, institutionCode);
            if (checkin != null) {
                return failed("此老人已存在,无需重复添加");
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);

            User user = userService.getByUserCode(elderly.getUserCode());

            CheckinSetmeal checkinSetmeal = null;

            //=1为根据套餐收费
            checkin = new Checkin();

            checkinSetmeal = checkinSetmealService.getByCheckinSetmealCode(checkinSetmealCode);
            checkin.setCheckinSetmealCode(checkinSetmealCode);
            checkin.setCheckinSetmealName(checkinSetmeal.getName());
            price = checkinSetmeal.getUnivalence();
            checkin.setPrice(price);

            Berth berth = berthService.getByBerthCode(berthCode);
            if (berth == null) {
                return failed("此床位不存在");
            }
            if (berth.getStatus() == 1) {
                return failed("此床位已住人，不可重复选择");
            }
            berth.setStatus(1);//床位设置为已预约

            checkin.setCheckinCode(UUID.randomUUID().toString());
            checkin.setBerthCode(berthCode);
            checkin.setBerthNumber(berth.getNumber());
            checkin.setElderlyCode(elderlyCode);
            checkin.setElderlyName(user.getName());
            checkin.setCreateTime(new Date());
            checkin.setType(type);

            checkin.setChargeType(chargeType);
            checkin.setStaffCode(staffCode);
            checkin.setInstitutionCode(institutionCode);
            checkin.setStatus(1);

            checkinService.insertAndUpdateBerthStatus(checkin, berth, feeArr);


            elderly.setAssessSpanDay(30);//设置评估间隔是30天
            elderly.setCheckinStatus(1);
            elderlyService.update(elderly);



            String dd = sdfYMD.format(new Date());
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(sdfYMD.parse(dd));
            calendar.add(calendar.DATE, 30);
            Date next = calendar.getTime();

            ElderlyCheckinAssessWait elderlyCheckinAssessWait = new ElderlyCheckinAssessWait();
            elderlyCheckinAssessWait.setElderlyCheckinAssessWaitCode(UUID.randomUUID().toString());
            elderlyCheckinAssessWait.setElderlyCode(elderlyCode);
            elderlyCheckinAssessWait.setCreateTime(next);
            elderlyCheckinAssessWait.setInstitutionCode(elderly.getInstitutionCode());
            elderlyCheckinAssessWait.setGovernmentCode(elderly.getGovernmentCode());
            elderlyCheckinAssessWaitService.insert(elderlyCheckinAssessWait);



            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/Checkin/Add", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    /**
     * 修改未办理入住的资料
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "Edit", method = RequestMethod.POST)
    public MyResult update(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String elderlyCode = jsonObject.getString("elderlyCode");
            String checkinSetmealCode = jsonObject.getString("checkinSetmealCode");
            String berthCode = jsonObject.getString("berthCode");

            //String beginTimePlan = jsonObject.getString("beginTimePlan");
            //String endTimePlan = jsonObject.getString("endTimePlan");
            //int chargeType = jsonObject.getInteger("chargeType");
            //int type = jsonObject.getInteger("type");

            //入住单价元/天
            double price = 0;

            JSONArray feeArr = jsonObject.getJSONArray("feeArr");
            String checkinCode = jsonObject.getString("checkinCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            Checkin checkin = checkinService.getByElderlyCodeAndInstitutionCode(elderlyCode, institutionCode);
            if (checkin != null) {
                if (!checkin.getCheckinCode().equals(checkinCode)) {
                    return failed("此老人已存在");
                }
            } else {
                checkin = checkinService.getByCheckinCode(checkinCode);
                if (checkin == null) {
                    return failed("数据不存在");
                }
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            User user = userService.getByUserCode(elderly.getUserCode());

            CheckinSetmeal checkinSetmeal = null;
            checkinSetmeal = checkinSetmealService.getByCheckinSetmealCode(checkinSetmealCode);
            checkin.setCheckinSetmealCode(checkinSetmealCode);
            checkin.setCheckinSetmealName(checkinSetmeal.getName());
            price = checkinSetmeal.getUnivalence();
            checkin.setPrice(price);


            //计算居住天数
//            int durationPlan = Util.caculateTotalTime(beginTimePlan, endTimePlan);
//            if (durationPlan <= 0) {
//                return failed("入住天数不能小于等于0");
//            }
            //计算预计费用
            //double moneyPlan = DoubleUtil.mul(price, (double) durationPlan);

            Berth berth = berthService.getByBerthCode(berthCode);

            //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            //Date beginTime1 = formatter.parse(beginTimePlan);
            //Date endTime1 = formatter.parse(endTimePlan);


            checkin.setElderlyCode(elderlyCode);
            checkin.setElderlyName(user.getName());
            //checkin.setDurationPlan(durationPlan);
            //checkin.setMoneyPlan(moneyPlan);
            //checkin.setBeginTimePlan(beginTime1);
            //checkin.setEndTimePlan(endTime1);

            //checkin.setType(type);

            checkinService.updateByCheckinCode(checkin, berth, feeArr);



            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/Checkin/Edit", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    @RequestMapping(value = "UploadContractImg", method = RequestMethod.POST)
    public MyResult UploadContractImg(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String checkinCode = jsonObject.getString("checkinCode");
            String contractImg = jsonObject.getString("contractImg");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/UploadContractImg");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Checkin checkin = checkinService.getByCheckinCode(checkinCode);
            checkin.setContractImg(contractImg);
            checkinService.update(checkin);
            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/Checkin/UploadContractImg", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //套餐入住
    @RequestMapping(value = "CheckinToElderly", method = RequestMethod.POST)
    public MyResult CheckinToElderly(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String checkinCode = jsonObject.getString("checkinCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/CheckinToElderly");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Checkin checkin = checkinService.getByCheckinCode(checkinCode);
            if (checkin == null) {
                return failed("数据不存在");
            }

            checkin.setStatus(1);
            checkin.setBeginTime(new Date());

            Berth berth = berthService.getByBerthCode(checkin.getBerthCode());
            if (berth == null) {
                return failed("床位不存在");
            }
            berth.setStatus(2);
            checkinService.updateCheckinAndBerth(checkin, berth);


            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/Checkin/CheckinToElderly", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }





    //列表
    @RequestMapping(value = "Page", method = RequestMethod.POST)
    public MyResult page(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String elderlyName = jsonObject.getString("elderlyName");
            String startTime = jsonObject.getString("startTime");
            String endTime = jsonObject.getString("endTime");
            int status = jsonObject.getInteger("status");
            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();
            if (endTime != null && !endTime.equals("")) {
                endTime = Util.timeAddDay(endTime, 1);
            }
            PageInfo<Checkin> checkinPageInfo = checkinService.getPageList(pageIndex, pageSize, institutionCode, elderlyName, status, startTime, endTime);
            List<CheckinDTO> checkinDTOList = new ArrayList<>();
            for (Checkin checkin : checkinPageInfo.getList()) {
                CheckinDTO checkinDTO = mapper.map(checkin, CheckinDTO.class);
                checkinDTOList.add(checkinDTO);
            }
            for (CheckinDTO checkinDTO : checkinDTOList) {
                Elderly elderly = elderlyService.getByElderlyCode(checkinDTO.getElderlyCode());
                if (elderly != null) {
                    checkinDTO.setBalance(elderly.getBalance());
                    User user = userService.getByUserCode(elderly.getUserCode());
                    checkinDTO.setElderlyName(user.getName());
                }
//                //统计充值金额
//                List<RechargeRecord> rechargeRecordList = rechargeRecordService.getByElderlyCode(checkinDTO.getElderlyCode());
//                if (rechargeRecordList == null) {
//                    checkinDTO.setAddBalance(0);
//                } else {
//                    double addBalance = 0;
//                    for (RechargeRecord rechargeRecord : rechargeRecordList) {
//                        addBalance = addBalance + rechargeRecord.getAddBalance();
//                    }
//                    checkinDTO.setAddBalance(addBalance);
//                }
                //统计消费金额
                List<RetreatSettle> retreatSettleList = retreatSettleService.getByElderlyCode(checkinDTO.getElderlyCode());
                if (retreatSettleList == null) {
                    checkinDTO.setCutBalance(0);
                } else {
                    double total = 0;
                    for (RetreatSettle retreatSettle : retreatSettleList) {
                        total = DoubleUtil.add(total,retreatSettle.getTotal());
                    }
                    checkinDTO.setCutBalance(total);
                }
                Berth berth = berthService.getByBerthCode(checkinDTO.getBerthCode());
                checkinDTO.setBerthNumber(berth.getNumber());
                if (berth == null) {
                    return failed("床位不存在");
                }
                Room room = roomService.getByRoomCode(berth.getRoomCode());
                if (room == null) {
                    return failed("房间不存在");
                }
                String roomNumber = room.getNumber();
                Building building = buildingService.getByBuildingCode(room.getBuildingCode());
                if (building == null) {
                    return failed("楼宇不存在");
                }
                String buildingName = building.getName();
                checkinDTO.setLiveAddress(buildingName + "-" + roomNumber + "-" + checkinDTO.getBerthNumber());
            }
            checkinPageInfo.setList(Collections.unmodifiableList(checkinDTOList));

            return success(checkinPageInfo);

        } catch (Exception e) {
            insertError("/Checkin/Page", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }



    //点击结算按钮返回结算金额
    @RequestMapping(value = "SettleMoney", method = RequestMethod.POST)
    public MyResult SettleMoney(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String checkinCode = jsonObject.getString("checkinCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/SettleMoney");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Checkin checkin = checkinService.getByCheckinCode(checkinCode);
            if (checkin == null) {
                return failed("该老人未入住");
            }

            Elderly elderly = elderlyService.getByElderlyCode(checkin.getElderlyCode());
            Date beginTime = checkin.getBeginTime();
            Date endTime = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String beTime = dateFormat.format(beginTime);
            String eTime = dateFormat.format(endTime);
            int days = Util.caculateTotalTime(beTime, eTime);
            if (days < 0) {
                return failed("费用异常，入住天数为负数");
            }
            double moneyPlan = DoubleUtil.mul(checkin.getPrice(), (double) days);
            if (moneyPlan < 0) {
                return failed("费用为负数：" + moneyPlan + "，请检查");
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("moneyPlan", moneyPlan);
            jsonObject1.put("elderly", elderly);
            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Checkin/SettleMoney", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //退住结算，修改床位，房间状态
    @RequestMapping(value = "RetreatSettle", method = RequestMethod.POST)
    public MyResult RetreatSettle(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String checkinCode = jsonObject.getString("checkinCode");
            String remarks = jsonObject.getString("remarks");
            double total = jsonObject.getDouble("total");//结算总金额
            int isRefund = jsonObject.getInteger("isRefund");//是否退款，1：退款，2：不退款
            double refundMoney = jsonObject.getDouble("refundMoney");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/RetreatSettle");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();
            Checkin checkin = checkinService.getByCheckinCode(checkinCode);
            if (checkin == null) {
                return failed("入住信息不存在");
            }
            if (checkin.getStatus() != 1) {
                return failed("请先办理入住后在结算");
            }
            String elderlyCode = checkin.getElderlyCode();
            checkin.setEndTime(new Date());
            checkin.setStatus(2);

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            double balance = elderly.getBalance();
            User user = userService.getByUserCode(elderly.getUserCode());
            if (total > balance) {
                return failed("老人账户余额不足");
            }

            Berth berth = berthService.getByBerthCode(checkin.getBerthCode());
            berth.setStatus(0);


            RetreatSettle retreatSettle = new RetreatSettle();
            if (isRefund == 1) {//退款
                double sum = DoubleUtil.sub(balance, DoubleUtil.add(total, refundMoney));
                if (sum != 0 || sum < 0) {
                    return failed("退款金额异常，请核对后在结算");
                }
            }
            if (isRefund == 2) {
                refundMoney = 0;
            }
            retreatSettle.setRetreatSettleCode(UUID.randomUUID().toString());
            retreatSettle.setElderlyCode(elderlyCode);
            retreatSettle.setElderlyName(user.getName());
            retreatSettle.setRemarks(remarks);
            retreatSettle.setTotal(total);//结算金额
            retreatSettle.setCreateTime(new Date());
            retreatSettle.setStaffCode(staffCode);
            retreatSettle.setInstitutionCode(institutionCode);
            retreatSettle.setCheckinCode(checkinCode);
            retreatSettle.setElderlyBalance(balance - total);
            retreatSettle.setReturnBlance(refundMoney);//退款金额


            checkinService.updateToStatus2(checkin, retreatSettle, elderlyCode, berth, isRefund);

            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/Checkin/RetreatSettle", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }


    //套餐入住转房
    @RequestMapping(value = "RoomChange", method = RequestMethod.POST)
    public MyResult RoomChange(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String checkinCode = jsonObject.getString("checkinCode");
            String newBerthCode = jsonObject.getString("berthCode");
            String remarks = jsonObject.getString("remarks");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/RoomChange");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();
            Checkin checkin = checkinService.getByCheckinCode(checkinCode);
            if (checkin == null) {
                return failed("入住信息不存在");
            }
            if (checkin.getStatus() == 0) {
                return failed("未入住无需转房");
            }
            if (checkin.getStatus() == 2) {
                return failed("已退住不可转房");
            }

            if (checkin.getBerthCode().equals(newBerthCode)) {
                return failed("未改变床位，无需转房");
            }


            Elderly elderly = elderlyService.getByElderlyCode(checkin.getElderlyCode());
            User user = userService.getByUserCode(elderly.getUserCode());

            if (checkin.getChargeType() == 1) {
                CheckinSetmeal checkinSetmeal = checkinSetmealService.getByCheckinSetmealCode(checkin.getCheckinSetmealCode());
                if (checkinSetmeal == null) {
                    return failed("此套餐不存在");
                }
            }

            //计算费用
            Date oldBeginTime = checkin.getBeginTime();//入住开始时间
            Date endTime = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String beTime = dateFormat.format(oldBeginTime);
            String eTime = dateFormat.format(endTime);
            int days = Util.caculateTotalTime(beTime, eTime);
            if (days < 0) {
                return failed("费用异常，入住天数为负数");
            }
            double moneyPlan = DoubleUtil.mul(checkin.getPrice(), (double) days);
            if (moneyPlan < 0) {
                return failed("费用为负数：" + moneyPlan + "，请检查");
            }
            if (elderly.getBalance() < moneyPlan) {
                return failed("该老人账户余额不足，不能转房");
            }

            RetreatSettle retreatSettle = new RetreatSettle();
            retreatSettle.setRetreatSettleCode(UUID.randomUUID().toString());
            retreatSettle.setElderlyCode(checkin.getElderlyCode());
            retreatSettle.setElderlyName(user.getName());
            retreatSettle.setRemarks(remarks);
            retreatSettle.setTotal(moneyPlan);
            retreatSettle.setCreateTime(new Date());
            retreatSettle.setStaffCode(staffCode);
            retreatSettle.setInstitutionCode(institutionCode);
            retreatSettle.setCheckinCode(checkinCode);
            retreatSettle.setElderlyBalance(elderly.getBalance());
            retreatSettle.setReturnBlance(0);

            checkinService.RoomChangeToElderly(checkin, jsonObject, moneyPlan, retreatSettle);

            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/Checkin/RoomChange", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    /**
     * 根据berthCode和状态值查询入住的老人信息
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "CheckinByBerthCode", method = RequestMethod.POST)
    public MyResult CheckinByBerthCode(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String berthCode = jsonObject.getString("berthCode");
            int status = jsonObject.getInteger("status");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/CheckinByBerthCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Checkin checkin = checkinService.getByBerthCode(berthCode, status);
            return success(checkin);
        } catch (Exception e) {
            insertError("/Checkin/CheckinByBerthCode", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    /**
     * 根据elderlyCode查询入住的老人信息
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "CheckinByElderlyCode", method = RequestMethod.POST)
    public MyResult CheckinByElderlyCode(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String elderlyCode = jsonObject.getString("elderlyCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/CheckinByElderlyCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            List<Checkin> checkinList = checkinService.getListByElderlyCode(elderlyCode);
            return success(checkinList);
        } catch (Exception e) {
            insertError("/Checkin/CheckinByElderlyCode", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    /**
     * 统计
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "Percent", method = RequestMethod.POST)
    public MyResult Percent(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Checkin/Percent");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();
            //查找总共有多少床位
            int sumNum = 0;
            int count = 0;
            List<Room> roomList = roomService.getByInstitutionCodeAndStatusNot11(institutionCode);
            if (roomList.size() > 0) {
                for (Room room : roomList) {
                    List<Berth> berthList = berthService.getListByRoomCodeAndStatusNot11(room.getRoomCode());
                    sumNum = sumNum + berthList.size();
                    for (Berth berth : berthList) {
                        if (berth.getStatus() == 1) {
                            count++;
                        }
                    }
                }
            }
            double percent = 0;
            if (sumNum != 0) {
                percent = DoubleUtil.divide((double) count, (double) sumNum, 2);
            }
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("percent", percent);
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Checkin/Percent", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    /**
     * 客户端
     * 根据老人code查询老人入住列表
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "GetCheckinByElderlyCode", method = RequestMethod.POST)
    public MyResult GetCheckinByElderlyCode(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");
            String elderlyCode = jsonObject.getString("elderlyCode");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Checkin/GetCheckinByElderlyCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            List<Checkin> checkinList = checkinService.getListByElderlyCode(elderlyCode);
            List<CheckinDTO1> checkinDTO1List = new ArrayList<>();
            for (Checkin checkin : checkinList) {
                CheckinDTO1 checkinDTO1 = mapper.map(checkin, CheckinDTO1.class);
                Berth berth = berthService.getByBerthCode(checkinDTO1.getBerthCode());
                checkinDTO1.setBerthNumber(berth.getNumber());
                if (berth == null) {
                    return failed("床位不存在");
                }
                Room room = roomService.getByRoomCode(berth.getRoomCode());
                if (room == null) {
                    return failed("房间不存在");
                }
                String roomNumber = room.getNumber();
                Building building = buildingService.getByBuildingCode(room.getBuildingCode());
                if (building == null) {
                    return failed("楼宇不存在");
                }
                String buildingName = building.getName();
                checkinDTO1.setLiveAddress(buildingName + "-" + roomNumber + "-" + checkinDTO1.getBerthNumber());
                checkinDTO1List.add(checkinDTO1);
            }
            for (CheckinDTO1 checkinDTO1 : checkinDTO1List) {
                //查对应入住的入住套餐
                String checkinSetmealCode = checkinDTO1.getCheckinSetmealCode();
                CheckinSetmeal checkinSetmeal = checkinSetmealService.getByCheckinSetmealCode(checkinSetmealCode);
                CheckinSetmealDTO1 checkinSetmealDTO1 = mapper.map(checkinSetmeal, CheckinSetmealDTO1.class);
                //查护理等级
                String nursingLevelCode = checkinSetmealDTO1.getNursingLevelCode();
                NursingLevel nursingLevel = nursingLevelService.getByNursingLevelCode(nursingLevelCode);
                NursingLevelDTO nursingLevelDTO = mapper.map(nursingLevel, NursingLevelDTO.class);
                //查护理等级包含的护理项目
                List<NursingLevelItemRel> nursingLevelItemRelList = nursingLevelItemRelService.getByNursingLevelCode(nursingLevelDTO.getNursingLevelCode());
                List<NursingItem> nursingItemList = new ArrayList<>();
                for (NursingLevelItemRel nursingLevelItemRel : nursingLevelItemRelList) {
                    NursingItem nursingItem = nursingItemService.getByNursingItemCode(nursingLevelItemRel.getNursingItemCode());
                    nursingItemList.add(nursingItem);
                }
                nursingLevelDTO.setNursingItemList(nursingItemList);

                checkinSetmealDTO1.setNursingLevelDTO(nursingLevelDTO);
                checkinDTO1.setCheckinSetmealDTO1(checkinSetmealDTO1);
            }

            return success(checkinDTO1List);

        } catch (Exception e) {
            insertError("/Checkin/GetCheckinByElderlyCode", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    /**
     * 客户端
     * 根据入住code查询入住详情
     *
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "GetByCheckinCode", method = RequestMethod.POST)
    public MyResult GetByCheckinCode(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");
            String checkinCode = jsonObject.getString("checkinCode");
            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Checkin/GetByCheckinCode");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Checkin checkin = checkinService.getByCheckinCode(checkinCode);
            CheckinDTO1 checkinDTO1 = mapper.map(checkin, CheckinDTO1.class);
            Berth berth = berthService.getByBerthCode(checkinDTO1.getBerthCode());
            if (berth == null) {
                return failed("床位不存在");
            }
            checkinDTO1.setBerthNumber(berth.getNumber());
            Room room = roomService.getByRoomCode(berth.getRoomCode());
            if (room == null) {
                return failed("房间不存在");
            }
            RoomType roomType = roomTypeService.getByRoomTypeCode(room.getRoomTypeCode());

            String roomNumber = room.getNumber();
            Building building = buildingService.getByBuildingCode(room.getBuildingCode());
            if (building == null) {
                return failed("楼宇不存在");
            }
            String buildingName = building.getName();
            checkinDTO1.setRoomTypeDTO(roomType);
            checkinDTO1.setLiveAddress(buildingName + "-" + roomNumber + "-" + checkinDTO1.getBerthNumber());
//            if(checkin){
//
//            }
            String checkinSetmealCode = checkinDTO1.getCheckinSetmealCode();
            CheckinSetmeal checkinSetmeal = checkinSetmealService.getByCheckinSetmealCode(checkinSetmealCode);
            CheckinSetmealDTO1 checkinSetmealDTO1 = mapper.map(checkinSetmeal, CheckinSetmealDTO1.class);
            //查护理等级
            String nursingLevelCode = checkinSetmealDTO1.getNursingLevelCode();
            NursingLevel nursingLevel = nursingLevelService.getByNursingLevelCode(nursingLevelCode);
            NursingLevelDTO nursingLevelDTO = mapper.map(nursingLevel, NursingLevelDTO.class);
            //查护理等级包含的护理项目
            List<NursingLevelItemRel> nursingLevelItemRelList = nursingLevelItemRelService.getByNursingLevelCode(nursingLevelDTO.getNursingLevelCode());
            List<NursingItem> nursingItemList = new ArrayList<>();
            for (NursingLevelItemRel nursingLevelItemRel : nursingLevelItemRelList) {
                NursingItem nursingItem = nursingItemService.getByNursingItemCode(nursingLevelItemRel.getNursingItemCode());
                nursingItemList.add(nursingItem);
            }
            nursingLevelDTO.setNursingItemList(nursingItemList);

            checkinSetmealDTO1.setNursingLevelDTO(nursingLevelDTO);
            checkinDTO1.setCheckinSetmealDTO1(checkinSetmealDTO1);

            return success(checkinDTO1);

        } catch (Exception e) {
            insertError("/Checkin/GetByCheckinCode", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

}
